"""
    A base class for Partner Gate unit tests.
"""

from pgate.gate import create_app
import unittest
from flask import Flask, Response
import types


class PartnerGateBaseTestCase(unittest.TestCase):
    """This contains base methods for easy partner gate testing."""

    def setUp(self):
        """Setup the test client."""
        self.app = create_app().test_client()

    def tearDown(self):
        """Teardown the test client."""
        # cleanup from tests?
        pass

    # utility methods
    def assert200(self, response):
        """Test the http response code is equal to 200."""
        self.assert_status(response, 200)

    def assert_status(self, response, status_code):
        """Test the http response code is equal to status_code."""
        self.assertEqual(response.status_code, status_code)

    def assert_url_response(self, partner_id, url):
        """Test the url response is valid."""
        response = self.app.get("/%s/%s" % (partner_id, url))
        self.assert200(response)
        self.assert_url_headers(response)
        self.assertNotEqual(response, "0")
        return response.data

    def assert_header(self, response, header, value):
        """Test the header exists in response.headers
           and the value is equal to value."""
        self.assertTrue(header in response.headers)
        self.assertEqual(response.headers[header], value)

    def assert_url_headers(self, response):
        """Test url response has the right headers."""
        self.assert_header(response, 'Content-type', 'text/javascript')
        self.assert_header(response, 'Cache-Control', 'max-age=604800')
        self.assert_header(response, 'Expires', '+7d')

    def assert_total_headers(self, response):
        """Test total response has the right headers."""
        self.assert_header(response, 'Content-type', 'text/javascript')
        self.assert_header(response, 'Cache-Control', 'max-age=3600')
        self.assert_header(response, 'Expires', '+1h')

    def assert_total_response(self, partner_id):
        """Test the total response is valid."""
        response = self.app.get("/total/%s/" % partner_id)
        self.assert200(response)
        self.assert_total_headers(response)
        self.assertTrue(is_int(response.data))
        return response.data


def is_int(str):
    """Test whether a string represents an integer."""
    try:
        int(str)
        return True
    except ValueError:
        return Flase
